package cn.project.dao;

import cn.project.model.User;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component("NamedParameter")
public class NamedParameterJdbcTemImple implements UserTempDao {

    /*主要是想需要写入
    *namedParameterJdbcTemImple
    * */
    @Resource(name = "namedParameterJdbcTemImple")
    private NamedParameterJdbcTemplate namedParameterJdbcTemImple;
    public static final RowMapper rowMapper=new ParameterizedRowMapper() {

        public Object mapRow(ResultSet resultSet, int i) throws SQLException {
            User  user=new User();
            user.setUserid(resultSet.getInt("userid"));
            user.setUsername(resultSet.getString("username"));
            user.setPassword(resultSet.getString("password"));
            return user;
        }
    };


    public List<User> getAllUser() {
       String sql="select * from user";
        List<User>list=namedParameterJdbcTemImple.query(sql,new HashMap(),rowMapper);
        return list;
    }

    public List <User> getAllUser(User user) {
        return null;
    }

    public User findById(int userid) {
        String sql="select * from user where userid=:id";
        Map params=new HashMap();
        params.put("id",userid);
        List<User>list=namedParameterJdbcTemImple.query(sql,params,rowMapper);

        return list.size()>0 ? list.get(0):null;
    }

    public int save(User user) {
        String sql = "insert into user(username,password) values (:name,:pass)";
        Map map = new HashMap();
        map.put("name",user.getUsername());
        map.put("pass",user.getPassword());
         return namedParameterJdbcTemImple.update(sql,map);
    }

    public int update(User user) {
        String sql="update user set username=:name where userid=:id ";
        Map params=new HashMap();
        params.put("name",user.getUsername());
        params.put("id",user.getUserid());
        return namedParameterJdbcTemImple.update(sql,params);

    }

    public int delete(int userid) {

        return userid;
    }

    public NamedParameterJdbcTemplate getNamedParameterJdbcTemImple() {
        return namedParameterJdbcTemImple;
    }

    public void setNamedParameterJdbcTemImple(NamedParameterJdbcTemplate namedParameterJdbcTemImple) {
        this.namedParameterJdbcTemImple = namedParameterJdbcTemImple;
    }
}
